package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址
     *
     * @param dto
     */
    @Override
    public void addAddress(AddressBookUpsertReqDTO dto) {
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getAddress, dto.getAddress());
        AddressBook addressBook = this.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(addressBook)) {
            throw new CommonException("地址存在无法重复添加");
        }
        AddressBook addressBook1 = BeanUtils.copyProperties(dto, AddressBook.class);
        Integer isDefault = addressBook1.getIsDefault();
        LambdaQueryWrapper<AddressBook> queryWrapper1 = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getIsDefault, isDefault);
        int count = this.count(queryWrapper1);
        if (count>0){
            throw new CommonException("已有一个默认地址，无法重复设置默认地址");
        }
        addressBook1.setUserId(UserContext.currentUserId());
        boolean result = this.save(addressBook1);
        if (!result) {
            throw new DBException("操作失败");
        }
    }

    /**
     * 地址簿分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBook> addressBookPage(AddressBookPageQueryReqDTO dto) {
        Page<AddressBook> page = PageUtils.parsePageQuery(dto, AddressBook.class);
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId());
        Page<AddressBook> page1 = this.page(page, queryWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setList(page1.getRecords());
        pageResult.setPages(page1.getPages());
        return pageResult;
    }

    /**
     * 根据Id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressBookById(Long id) {
        AddressBook addressBook = this.getById(id);
        if (ObjectUtil.isEmpty(addressBook)) {
            throw new CommonException("地址不存在");
        }
        return addressBook;
    }

    /**
     * 根据Id修改地址
     *
     * @param id
     * @return
     */
    @Override
    public void modifyAddressBookById(Long id, AddressBookUpsertReqDTO dto) {
        AddressBook addressBook = this.getById(id);
        if (ObjectUtil.isEmpty(addressBook)) {
            throw new CommonException("地址不存在");
        }
        AddressBook addressBook1 = BeanUtils.copyProperties(dto, AddressBook.class);
        if (ObjectUtil.isEmpty(addressBook1)) {
            throw new CommonException("地址不存在");
        }
        LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate().eq(AddressBook::getId, id);
        boolean update = this.update(addressBook1, updateWrapper);
        if (!update) {
            throw new DBException("操作失败");
        }
    }

    /**
     * 根据Id批量删除地址
     *
     * @param ids
     */
    @Override
    public void deleteAddressBookById(List<Long> ids) {
        for (Long id : ids) {
            AddressBook addressBook = this.getById(id);
            if (ObjectUtil.isEmpty(addressBook)) {
                throw new CommonException("地址不存在");
            }
            boolean result = this.removeById(id);
            if (!result) {
                throw new DBException("操作失败");
            }
        }
    }

    /**
     * 设置/取消默认地址
     *
     * @param id
     * @param flag
     */
    @Override
    public void defaultAddressBookById(Long id, Integer flag) {
        AddressBook addressBook = this.getById(id);
        if (ObjectUtil.isEmpty(addressBook)) {
            throw new CommonException("地址不存在");
        }
        Integer isDefault = addressBook.getIsDefault();
        if (flag == CertificationStatusEnum.INIT.getStatus()) {
            if (flag.equals(isDefault)) {
                throw new CommonException("不能重复取消默认地址");
            }
            LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate().set(AddressBook::getIsDefault, flag).eq(AddressBook::getId, id);
            boolean update = this.update(updateWrapper);
            if (!update) {
                throw new DBException("操作失败");
            }
        }
        if (flag == CertificationStatusEnum.PROGRESSING.getStatus()) {
            LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId());
            List<AddressBook> list = this.list(queryWrapper);
            for (AddressBook book : list) {
                if (book.getIsDefault() == CertificationStatusEnum.PROGRESSING.getStatus()) {
                    throw new CommonException("已存在一个默认地址，无法再设置一个默认地址");
                }
            }
            if (flag.equals(isDefault)) {
                throw new CommonException("不能重复设置默认地址");
            }
            LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate().set(AddressBook::getIsDefault, flag).eq(AddressBook::getId, id);
            boolean update = this.update(updateWrapper);
            if (!update) {
                throw new DBException("操作失败");
            }
        }
    }

    /**
     * 获取默认地址接口
     * @return
     */
    @Override
    public AddressBook defaultAddress() {
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId()).eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING.getStatus());
        AddressBook addressBook = this.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(addressBook)) {
            throw new CommonException("默认地址不存在");
        }
        return addressBook;
    }
}
